// 设置导入导出工具
// 处理设置的导入导出功能

import { SettingsConfig, SettingsExport } from '../types/settings';

export class SettingsImportExport {
  // 导出设置到文件
  static exportToFile(settings: SettingsConfig, filename?: string): void {
    const exportData: SettingsExport = {
      version: '1.0.0',
      timestamp: Date.now(),
      settings,
      metadata: {
        appVersion: '1.0.0',
        platform: navigator.platform,
        exportedBy: 'CodeGraph Editor'
      }
    };

    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: 'application/json'
    });

    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename || `codegraph-settings-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  // 从文件导入设置
  static importFromFile(): Promise<SettingsExport | null> {
    return new Promise((resolve) => {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.json';
      
      input.onchange = async (e) => {
        const file = (e.target as HTMLInputElement).files?.[0];
        if (!file) {
          resolve(null);
          return;
        }

        try {
          const text = await file.text();
          const data = JSON.parse(text);
          
          // 验证导入数据格式
          if (this.validateImportData(data)) {
            resolve(data as SettingsExport);
          } else {
            console.error('Invalid settings file format');
            resolve(null);
          }
        } catch (error) {
          console.error('Failed to parse settings file:', error);
          resolve(null);
        }
      };

      input.click();
    });
  }

  // 验证导入数据格式
  private static validateImportData(data: any): boolean {
    if (!data || typeof data !== 'object') {
      return false;
    }

    // 检查必需字段
    if (!data.version || !data.timestamp || !data.settings) {
      return false;
    }

    // 检查版本兼容性
    if (!this.isVersionCompatible(data.version)) {
      return false;
    }

    // 检查设置数据结构
    if (typeof data.settings !== 'object') {
      return false;
    }

    return true;
  }

  // 检查版本兼容性
  private static isVersionCompatible(version: string): boolean {
    const supportedVersions = ['1.0.0'];
    return supportedVersions.includes(version);
  }

  // 导出特定分类的设置
  static exportCategory(settings: SettingsConfig, category: keyof SettingsConfig): SettingsExport {
    const categorySettings = { [category]: settings[category] };
    
    return {
      version: '1.0.0',
      timestamp: Date.now(),
      settings: categorySettings as Partial<SettingsConfig>,
      metadata: {
        appVersion: '1.0.0',
        platform: navigator.platform,
        exportedBy: 'CodeGraph Editor'
      }
    };
  }

  // 导出用户自定义设置（与默认值不同的设置）
  static exportCustomSettings(currentSettings: SettingsConfig, defaultSettings: SettingsConfig): SettingsExport {
    const customSettings: Partial<SettingsConfig> = {};

    // 比较当前设置与默认设置
    Object.entries(currentSettings).forEach(([category, categorySettings]) => {
      const defaultCategorySettings = defaultSettings[category as keyof SettingsConfig];
      const customCategorySettings: any = {};
      let hasCustomSettings = false;

      Object.entries(categorySettings as any).forEach(([key, value]) => {
        const defaultValue = (defaultCategorySettings as any)?.[key];
        if (JSON.stringify(value) !== JSON.stringify(defaultValue)) {
          customCategorySettings[key] = value;
          hasCustomSettings = true;
        }
      });

      if (hasCustomSettings) {
        (customSettings as any)[category] = customCategorySettings;
      }
    });

    return {
      version: '1.0.0',
      timestamp: Date.now(),
      settings: customSettings,
      metadata: {
        appVersion: '1.0.0',
        platform: navigator.platform,
        exportedBy: 'CodeGraph Editor'
      }
    };
  }

  // 合并导入的设置
  static mergeSettings(currentSettings: SettingsConfig, importedSettings: Partial<SettingsConfig>): SettingsConfig {
    const mergedSettings = { ...currentSettings };

    Object.entries(importedSettings).forEach(([category, categorySettings]) => {
      if (categorySettings && typeof categorySettings === 'object') {
        const categoryKey = category as keyof SettingsConfig;
        (mergedSettings as any)[categoryKey] = {
          ...(mergedSettings as any)[categoryKey],
          ...categorySettings
        };
      }
    });

    return mergedSettings;
  }

  // 创建设置备份
  static createBackup(settings: SettingsConfig): string {
    const backup: SettingsExport = {
      version: '1.0.0',
      timestamp: Date.now(),
      settings,
      metadata: {
        appVersion: '1.0.0',
        platform: navigator.platform,
        exportedBy: 'CodeGraph Editor'
      }
    };

    return JSON.stringify(backup);
  }

  // 从备份恢复设置
  static restoreFromBackup(backupData: string): SettingsConfig | null {
    try {
      const data = JSON.parse(backupData);
      
      if (this.validateImportData(data)) {
        return data.settings;
      }
      
      return null;
    } catch (error) {
      console.error('Failed to restore from backup:', error);
      return null;
    }
  }

  // 生成设置摘要
  static generateSettingsSummary(settings: SettingsConfig): string {
    const summary = [];
    
    summary.push('# 设置摘要');
    summary.push(`导出时间: ${new Date().toLocaleString()}`);
    summary.push('');

    Object.entries(settings).forEach(([category, categorySettings]) => {
      summary.push(`## ${this.getCategoryDisplayName(category)}`);
      
      Object.entries(categorySettings as any).forEach(([key, value]) => {
        summary.push(`- ${key}: ${JSON.stringify(value)}`);
      });
      
      summary.push('');
    });

    return summary.join('\n');
  }

  // 获取分类显示名称
  private static getCategoryDisplayName(category: string): string {
    const displayNames: Record<string, string> = {
      editor: '编辑器',
      appearance: '外观',
      keyboard: '快捷键',
      files: '文件',
      extensions: '扩展',
      advanced: '高级'
    };
    
    return displayNames[category] || category;
  }

  // 验证设置值的有效性
  static validateSettingsValues(settings: Partial<SettingsConfig>): { isValid: boolean; errors: string[] } {
    const errors: string[] = [];

    // 验证编辑器设置
    if (settings.editor) {
      const editor = settings.editor;
      
      if (editor.fontSize !== undefined) {
        if (typeof editor.fontSize !== 'number' || editor.fontSize < 8 || editor.fontSize > 72) {
          errors.push('编辑器字体大小必须在8-72之间');
        }
      }
      
      if (editor.tabSize !== undefined) {
        if (typeof editor.tabSize !== 'number' || editor.tabSize < 1 || editor.tabSize > 8) {
          errors.push('制表符大小必须在1-8之间');
        }
      }
    }

    // 验证外观设置
    if (settings.appearance) {
      const appearance = settings.appearance;
      
      if (appearance.theme !== undefined) {
        const validThemes = ['light', 'dark', 'auto'];
        if (!validThemes.includes(appearance.theme)) {
          errors.push('主题值无效');
        }
      }
      
      if (appearance.accentColor !== undefined) {
        if (typeof appearance.accentColor !== 'string' || !this.isValidColor(appearance.accentColor)) {
          errors.push('强调色格式无效');
        }
      }
    }

    // 验证高级设置
    if (settings.advanced) {
      const advanced = settings.advanced;
      
      if (advanced.maxMemoryUsage !== undefined) {
        if (typeof advanced.maxMemoryUsage !== 'number' || advanced.maxMemoryUsage < 256 || advanced.maxMemoryUsage > 8192) {
          errors.push('最大内存使用量必须在256-8192MB之间');
        }
      }
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  // 验证颜色值
  private static isValidColor(color: string): boolean {
    const hexPattern = /^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/;
    return hexPattern.test(color);
  }

  // 获取设置差异
  static getSettingsDiff(oldSettings: SettingsConfig, newSettings: SettingsConfig): Record<string, { old: any; new: any }> {
    const diff: Record<string, { old: any; new: any }> = {};

    const compareObjects = (oldObj: any, newObj: any, prefix: string = '') => {
      const allKeys = new Set([...Object.keys(oldObj || {}), ...Object.keys(newObj || {})]);
      
      allKeys.forEach(key => {
        const fullKey = prefix ? `${prefix}.${key}` : key;
        const oldValue = oldObj?.[key];
        const newValue = newObj?.[key];
        
        if (typeof oldValue === 'object' && typeof newValue === 'object' && 
            oldValue !== null && newValue !== null && 
            !Array.isArray(oldValue) && !Array.isArray(newValue)) {
          compareObjects(oldValue, newValue, fullKey);
        } else if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
          diff[fullKey] = { old: oldValue, new: newValue };
        }
      });
    };

    compareObjects(oldSettings, newSettings);
    return diff;
  }
}
